<?php
namespace App\Library;

class Http {
    public static function request($url, $method = 'GET', $params = [], $timeout = 10, $extHeaders = []) {
        $ci = curl_init();
        curl_setopt($ci, CURLOPT_USERAGENT, 'JOYPAW.COM CLIENT');
        curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ci, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ci, CURLOPT_HEADER, false);
        $headers = (array)$extHeaders;
        $method  = strtoupper($method);
        switch($method) {
            case 'POST':
                curl_setopt($ci, CURLOPT_POST, true);
                if(!empty($params)) {
                    curl_setopt($ci, CURLOPT_POSTFIELDS, http_build_query($params));
                }
                break;
            case 'DELETE':
            case 'GET':
                $method == 'DELETE' && curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
                if(!empty($params)) {
                    $url = $url . (strpos($url, '?') ? '&' : '?') . (is_array($params) ? http_build_query($params) : $params);
                }
                break;
        }
        curl_setopt($ci, CURLINFO_HEADER_OUT, true);
        curl_setopt($ci, CURLOPT_URL, $url);
        if($headers) {
            curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
        }
        $response = curl_exec($ci);
        curl_close($ci);
        return $response;
    }
}